/*
 * @Author: YueLia
 * @Date: 2025-02-26 15:59:48
 * @LastEditors: YueLia
 * @LastEditTime: 2025-02-26 17:20:24
 * @Description: 
 */
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

// 创建异步 thunk 请求用户数据
export const fetchUsers = createAsyncThunk("users/fetchUsers", async () => {
  const response = await axios.get(
    "https://jsonplaceholder.typicode.com/users"
  );
  return response.data;
});

interface CounterState {
  value: number;
  userList: Array<number>;
  loading: boolean;
  error?: Error | null | String;
}
const initialState: CounterState = {
  value: 0,
  userList: [],
  loading: false,
};

export const counterSlice = createSlice({
  name: "global",
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },

  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.loading = false;
        // state.userList = action.payload.map((e) => {
        //   e.key = e.id;
        //   return e;
        // });
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      });
  },
});

// 为每个 case reducer 函数生成 Action creators
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;
